<!--
 * @Author: Junxu
 * @Date: 2024-07-18 13:55:29
 * @LastEditors: Junxu
 * @LastEditTime: 2024-07-31 20:34:00
 * @Description: 维修报告分享详情页，用于分享及发送
-->
<template>
  <view class="report-share">
    <view class="container">
      <view class="report-img-box">
        <image
          show-menu-by-longpress
          :src="imageUrl"
          mode="widthFix"
          class="report-img"
          @longpress="onLongTap"
        />
      </view>
    </view>
    <view class="report-share-header">
      <view class="report-share-btn">
        <image
          src="@/static/images/download_bule.png"
          mode="widthFix"
          class="report-icon"
        />
        <text @click="downloadPDF">下载PDF</text>
      </view>
      <view class="report-share-split"></view>
      <view class="report-share-btn" @click="showShareTip">
        <image
          src="@/static/images/share.png"
          mode="widthFix"
          class="report-icon"
        />
        <text>分享</text>
      </view>
    </view>
    <image :src="statusImageUrl" mode="widthFix" class="report-status-img" />
    <view class="report-share-footer" v-if="sendStatus != 2">
      <view class="btn-box">
        <view class="btn" @click="showShareTip">分享图片至客户</view>
        <view class="btn" @click="onSendReport">{{
          sendStatus == 1 ? "发送小程序通知至客户" : "重新发送"
        }}</view>
      </view>
    </view>
    <view v-show="showTip">
      <view class="share-tip">
        <image
          src="@/static/images/longTap.png"
          mode="widthFix"
          class="share-tip-img"
        ></image>
        <view>长按图片分享至微信</view>
      </view>
    </view>
	<previewMedia ref="previewMedia"></previewMedia>
  </view>
</template>
  
<script>
import { getReportDetail, addOrUpdateReport, sendReport, addSendReportLog } from '@/apis/repair';
export default {
	props: {},
	data() {
		return {
			statusList: [
				{
					id: 3,
					text: '发送失败',
					image:
            'https://erised-fresh.oss-cn-shenzhen.aliyuncs.com/592800/1721358563018_zig4pj3g.png',
				},
				{
					id: 2,
					text: '已发送',
					image:
            'https://erised-fresh.oss-cn-shenzhen.aliyuncs.com/592800/1721358563018_5oktigv8.png',
				},
				{
					id: 1,
					text: '待发送',
					image:
            'https://erised-fresh.oss-cn-shenzhen.aliyuncs.com/592800/1721358563017_pg3wixcx.png',
				},
			],
			showTip: false,
			imageUrl: '',
			pdfUrl: '',
			reportId: null,
			sendStatus: 1, // 发送状态 1-待发送 2-已发送 3-发送失败
			info: {
				elevatorAddress: '',
				updateTime: '',
			},
		};
	},
	watch: {},
	computed: {
		statusImageUrl() {
			return this.statusList.find((v) => v.id == this.sendStatus).image;
		},
	},
	async onLoad(e) {
		const { id } = e;
		this.reportId = id;
		this.getDetail();

		console.log('[reportShare] onLoad : ', e);
	},
	methods: {
		// 获取详情
		async getDetail() {
			uni.showLoading({
				title: '加载中',
			});
			try {
				const res = await getReportDetail({ reportId: this.reportId });
				console.log(res, 'res');
				uni.hideLoading();
				if (res && res.code == 200 && res.data) {
					if (!res.data.reportImg || !res.data.reportFile) {
						uni.redirectTo({
							url: `/subpages/repair/reportDetailH5?id=${this.reportId}`,
						});
						return;
					}
					this.imageUrl = res.data.reportImg;
					this.pdfUrl = res.data.reportFile;
					this.sendStatus = res.data.sendStatus;
					this.info = res.data;
					if (this.sendStatus === 3) {
						uni.showToast({
							title: '报告发送失败，尝试重新发送或分享图片至客户',
							icon: 'none',
						});
					}
				}
			} catch (error) {
				uni.hideLoading();
				console.log(error);
			}
		},
		showShareTip() {
			if (this.showTip) {
				return;
			}
			this.showTip = true;
			// 可以使用setTimeout模拟短暂显示后自动隐藏的效果
			setTimeout(() => {
				this.showTip = false;
			}, 5000); // 2秒后隐藏
		},
		previewImage() {
			this.$previewMedia({
				current:0,
				sources: [this.imageUrl],
			});
		},
		onLongTap() {
			if (this.sendStatus === 3) {
				this.updateReport();
			}
			this.onSendReportLog(3);
		},
		async onSendReport() {
			try {
				uni.showLoading({
					title: '加载中',
				});
				const res = await sendReport({ reportId: this.reportId });
				console.log(res, 'res');
				uni.hideLoading();
				if (res.code == 200 && res.data) {
					this.sendStatus = 2;
					uni.showToast({
						title: '报告已发送至客户',
						icon: 'none',
					});
				} else {
					this.sendStatus = 3;
					uni.showToast({
						title: '维修报告发送失败,请检查机器人配置',
						icon: 'none',
					});
				}
			} catch (error) {
				uni.hideLoading();
				this.sendStatus = 3;
				uni.showToast({
					title: '维修报告发送失败',
					icon: 'none',
				});
				console.log(error, 'onSendReport');
			}
		},
		// 下载PDF
		downloadPDF() {
			const parts = this.info.updateTime.split(' ')[0].split('-'); // 分割日期字符串，忽略时间部分
			const year = parts[0];
			const month = parts[1];
			const day = parts[2];
			const formattedDate = `${year}${month}${day}`;
			let fileName = `${this.info.elevatorAddress}维修报告${formattedDate}.pdf`;
			console.log(fileName, 'fileName');
			uni.showLoading({
				title: '下载中',
			});
			uni.downloadFile({
				url: this.pdfUrl,
				success: (res) => {
					console.log(res, '下载的文件');
					if (res.statusCode === 200) {
						const fs = uni.getFileSystemManager();
						fs.saveFile({
							tempFilePath: res.tempFilePath,
							filePath: wx.env.USER_DATA_PATH + '/' + fileName,
							success: (res) => {
								if (this.sendStatus === 3) {
									this.updateReport();
								}
								this.onSendReportLog(2);
								console.log(res, '下载的文件路径');
								uni.hideLoading();
								// uni.showToast({
								//   title: "下载成功",
								//   icon: "none",
								// });
								uni.openDocument({
									filePath: res.savedFilePath,
									showMenu: true,
									success: (res) => {},
								});
							},
						});
					}
				},
				fail: (err) => {
					uni.hideLoading();
				},
			});
		},
		// 更新发送记录
		async onSendReportLog(contentType) {
			try {
				let param = {
					reportId: this.reportId,
					contentType,
					status: 1
				};
				const res = await addSendReportLog(param);
				console.log(res, 'res');
				if (res.code == 200 && res.data) {
				}
			} catch (error) {
				uni.showToast({
					title: '发送记录更新失败',
					icon: 'none',
				});
				console.log(error, 'onSendReport');
			}
		},
		// 更新发送状态
		async updateReport() {
			try {
				const param = {
					id: this.reportId,
					sendStatus: 2
				};
				const res = await addOrUpdateReport(param);
				if (res && res.code == 200 && res.data) {
					this.sendStatus = 2;  
				}
			} catch (error) {
				console.log(error, 'updateReport');
			}
		},
	},
};
</script>

<style lang="scss" scoped>
.report-img {
  width: 100%;
  height: auto;
}
.report-share {
  position: relative;
  .report-status-img {
    width: 96rpx;
    // height: 96rpx;
    position: absolute;
    top: 95rpx;
    right: 48rpx;
  }
  &-footer {
    width: 100%;
    height: 100rpx;
    .btn-box {
      height: 100rpx;
      width: 100%;
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 3;
      padding: 16rpx;
      box-sizing: border-box;
      background-color: #ffffff;
      display: flex;
      .btn {
        flex: 1;
        width: 0;
        height: 100%;
        color: #ffffff;
        font-size: 28rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
        &-disabled {
          background-color: #cccccc;
          color: #ffffff;
        }
        &:nth-child(1) {
          border-top-left-radius: 8rpx;
          border-bottom-left-radius: 8rpx;
          background-color: #f5fbff;
          color: #0091ff;
        }
        &:nth-child(2) {
          border-top-right-radius: 8rpx;
          border-bottom-right-radius: 8rpx;
          background-color: #0091ff;
          color: #ffffff;
        }
      }
    }
  }
}
/* 全局样式或页面样式 */
.share-tip {
  position: fixed;
  z-index: 2;
  top: 0;
  bottom: 0; /* 根据需要调整位置 */
  left: 50%; /* 居中 */
  margin: auto 0;
  transform: translateX(-50%);
  color: #f3f6f8;
  background: rgba(51, 51, 51, 0.7);
  border-radius: 16rpx;
  width: 288rpx;
  height: 200rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  // transition: 0.3s all;
  &-img {
    width: 48rpx;
    height: auto;
    margin-bottom: 8rpx;
  }
}
.report-share-header {
  display: flex;
  position: absolute;
  top: 40rpx;
  right: 44rpx;
  align-items: center;
  .report-share-btn {
    display: flex;
    align-items: center;
    color: #0091ff;
    font-size: 24rpx;
    .report-icon {
      width: 28rpx;
      margin-right: 4rpx;
    }
  }
  .report-share-split {
    display: block;
    margin: 0 16rpx;
    width: 2rpx;
    height: 28rpx;
    background-color: #cccccc;
  }
}
</style>
